/**放生明细表操作 */
const cloud = require('wx-server-sdk')
cloud.init({env: 'evn-cloud-a-4gf1q6iy9df62d73'})
const db = cloud.database()
const _ = db.command
const $ = _.aggregate
const MAX_LIMIT = 100

const numberFormat = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

const dateFormatter = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const dateStr = `${[year, month, day].map(numberFormat).join('-')}`
  return dateStr
}
const getTotalCount = async (date) => {
  let _count = await db.collection('freeCaptiveDetails').where({freeDate: date, freeAmount: _.gt(0)}).count();
  // console.log('查询明细表总条数为：',_count)
  return _count.total
}
//根据页面大小和页号得到List
const getListBySkipAndLimit = async (date, skipCount, limitCount) => {
  const queryFreeCapResult = await db.collection('freeCaptiveDetails').aggregate().match({
    freeDate: date,
    freeAmount: _.gt(0)
  }).project({
    meritsVirtues: true,
    freeAmount: true,
    meritsVirtuesLen: $.strLenBytes('$meritsVirtues'),
    freeDate: true,
    balance: true,
    chargeAmount: true,
    isSelect: true
  }).sort({meritsVirtuesLen: -1, _id: -1}).skip(skipCount).limit(limitCount).end()
  console.log('skip: ', skipCount, 'limit: ', limitCount, '查询放生明细表结果为：', queryFreeCapResult)
  const list = queryFreeCapResult.list
  return (list != undefined)? list: []
}
/**得到总放生额和总余额 */
const getSumFreeAmountAndSumBalance = async (date,type) => {
  let data
  if(type=='findAll'){
    data = {freeDate: date}
  }else{
    data = {freeDate: date, freeAmount: _.gt(0)}
  }
  const querySumAmountResult = await db.collection('freeCaptiveDetails').aggregate().match(data).group({
    _id: '余额和放生额总额',
    sumBalance: $.sum('$balance'),
    sumFreeAmount: $.sum('$freeAmount')
  }).end()
  console.log('计算放生总金额和余额总金额的结果为：',querySumAmountResult)
  const item = querySumAmountResult.list[0]
  return [item.sumFreeAmount, item.sumBalance]
}
//把多个数组合并为一个
const merageArrays = async (tasks) => {
  const allList = (await Promise.all(tasks)).reduce((acc, cur) => { return acc.data.concat(cur.data)})
  console.log('allList: ',allList)
  return allList
}
const getNumber = (divid, divisor)=>{
  const k = Number(new String(divid / divisor).split('.')[0])
  const t = divid % divisor == 0 ? 0: 1
  return k + t
} 
const getHeightByLineCount = (lineCount) => {
  switch(lineCount){
    case 1:
      return 59.4
    case 2:
      return 97.8
    case 3:
      return 136.2
    case 4:
      return  174.6
    case 5: 
      return 213
    default:
      return 0      
  }
}
const getEntityBy20List = async (queryFreeCapList, availableHeight_in, gridNameWidth_in,type) => {
  let sumHeight = 0;
  let array = [];
  let k = 0;
  if(type==='previous'){
    // console.log('上一页被点击....')
    const len = queryFreeCapList.length - 1
    for(let i=len ; i >= 0; i--){
      const meritsLen = Number(queryFreeCapList[i].meritsVirtuesLen)
      const wordsNumber = await getNumber(meritsLen, 3)
      const totalLen = wordsNumber * 24
      const lineCount = await getNumber(totalLen, gridNameWidth_in)
      const height = await getHeightByLineCount(lineCount)
      sumHeight = height + sumHeight
      k = k + 1
      array[len-i] = queryFreeCapList[i]
      if(sumHeight > availableHeight_in){
        break;
      }
      console.log(height,sumHeight,availableHeight_in)
    }
    // console.log('输出的值为：',array)
    return {list: array, size: k}
  }
  // console.log('下一页被点击.....')
  for(let i=0; i < queryFreeCapList.length; i++){
    const meritsLen = Number(queryFreeCapList[i].meritsVirtuesLen)
    const wordsNumber = await getNumber(meritsLen, 3)
    const totalLen = wordsNumber * 24
    const lineCount = await getNumber(totalLen, gridNameWidth_in)
    const height = await getHeightByLineCount(lineCount)
    sumHeight = height + sumHeight
    k = i + 1
    array[i] = queryFreeCapList[i]
    if(sumHeight > availableHeight_in) break; 
  }
  return {list: array, size: k}
}

const findPage = async (event) => {
  console.log('\n\n\n分页查询,输入参数，event: ',event)
  let skip_in = Number(event.skip)
  const totalCount_in = Number(event.totalCount)
  const availableHeight_in = Number(event.availableHeight)
  const gridNameWidth_in = Number(event.gridNameWidth)
  const pageType = event.pageType
  let dat = event.dat
  const date = (dat != null && dat != '') ? dat: await dateFormatter(new Date())
  // console.log('变量（dat）的值为：',dat)
  
  let _totalCount = totalCount_in
  if(totalCount_in == 0 || totalCount_in == undefined)  _totalCount = await getTotalCount(date)
  /**上一页 TODO */
  if(pageType==='previousPage'){
    console.log('上一页被点击，skip_in:',skip_in) 
    const size = skip_in > 20 ? 20: skip_in
    skip_in = skip_in > 20 ? skip_in - 20 : 0
    skip_in = skip_in <= 0 ? 0: skip_in
    const queryFreeCapList = await getListBySkipAndLimit(date, skip_in, size)
    const entity = await getEntityBy20List(queryFreeCapList, availableHeight_in, gridNameWidth_in, 'previous')
    if(size == 20){
      // console.log('size的值为：20，skip_in:', skip_in)
      skip_in = 20 - Number(entity.size) + skip_in
      // console.log('skip_in: ',skip_in)
    }else if(size <= 20){
      // console.log('szie的值小于20')
      skip_in = size - entity.size
    }else{
      console.error('size长度不存在....')
    }
    console.log('返回的关键信息，skip_in:',skip_in,'pageSize: ',entity.size)
    const _sumAmountArr = await getSumFreeAmountAndSumBalance(date)
    const _result =  {code: 0000, errMsg: '成功.', data: { list: entity.list.reverse(), skip: skip_in, pageSize: entity.size, totalCount: _totalCount , sumFreeAmount: _sumAmountArr[0], sumBalance: _sumAmountArr[1]}}
    console.log('返回的结果为：',_result)
    return _result
  }
  //下一页 
  const queryFreeCapList = await getListBySkipAndLimit(date, skip_in , 20)
  const entity = await getEntityBy20List(queryFreeCapList, availableHeight_in, gridNameWidth_in)
  // console.log('分页查询结果：', queryFreeCapList,'将要返回的实体为：',entity)
  console.log('返回的关键信息，skip_in:', skip_in, 'pageSize: ', entity.size)

  const _sumAmountArr = await getSumFreeAmountAndSumBalance(date)
  const _result =  {code: 0000, errMsg: '成功.', data: { list: entity.list, skip: skip_in, pageSize: entity.size, totalCount: _totalCount , sumFreeAmount: _sumAmountArr[0], sumBalance: _sumAmountArr[1]}}
  console.log('返回的结果为：',_result)
  return _result
}
const findAll = async (event) => {
  let dat = event.dat
  const date = await dateFormatter(new Date())
  dat = (dat != null && dat != '') ? dat: date
  console.log('变量（dat）的值为：',dat, "传入的参数(event)为：",event,'\n')

  const queryResult = await db.collection('freeCaptiveDetails').where({ freeDate: dat }).count()    // 先取出集合记录总数
  const total = queryResult.total
  console.log("根据条件查询数据总条数结束，数据总条数(total)为：",total,'查询总条数返回的结果（queryResult）为：',queryResult)
  if(total == 0) { return { code: 2001, errMsg: "查询结果为空"} }
  const batchTimes = Math.ceil(total / 100)  // 计算需分几次取
  const tasks = []    // 承载所有读操作的 promise 的数组
  for (let i = 0; i < batchTimes; i++) {
    const promise = await db.collection('freeCaptiveDetails').where({ freeDate: dat }).skip(i * MAX_LIMIT).limit(MAX_LIMIT).get({})
    tasks.push(promise)
  }
  console.log('根据条件已查询到数据，合并后的数据(tasks)为：',tasks)
  const sumAmountArr = await getSumFreeAmountAndSumBalance(dat,'findAll')
  // 等待所有
  const list =await merageArrays(tasks)
  console.log('list: ',list)
  return {
    data: { list: list,  sumFreeAmount: sumAmountArr[0], sumBalance: sumAmountArr[1]},
    errMsg: '成功.',
    code: 0
  }
}
const main = async (event) => {
  // console.log('输入参数为：',event)
  const reqType = event.reqType
  switch(reqType){
    case 'findPage':
      return await findPage(event)
    default:
      return await findAll(event)    
  }
}

module.exports = {
  main,
}